<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="设备编号" prop="deviceNo">
            <el-input v-model="queryParams.deviceNo" placeholder="请输入设备编号" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="queryParams.deviceType" placeholder="请选择设备状态" clearable>
              <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="设备状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
              <el-option
                v-for="dict in device_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="收费类型" prop="feeType">
            <el-select v-model="queryParams.feeType" placeholder="请选择收费类型" clearable>
              <el-option
                v-for="dict in fee_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:device:add']">新增
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceList" border>
        <el-table-column type="index" width="55" align="center" fixed="left"/>
        <el-table-column label="设备ID" align="center" prop="deviceId" v-if="false"/>
        <el-table-column label="设备编号" align="center" prop="deviceNo" fixed="left" width="180"/>
        <el-table-column label="设备类型" align="center" prop="deviceType" width="100">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.deviceType"/>
          </template>
        </el-table-column>
        <el-table-column label="密码" align="center" prop="devicePwd" show-overflow-tooltip width="100" />
        <el-table-column label="场地ID" align="center" prop="positionId" v-if="false"/>
        <el-table-column label="场地名称" align="center" prop="positionName"/>
        <el-table-column label="设备名称" align="center" prop="name"/>
        <el-table-column label="设备描述" align="center" prop="describe"/>
        <el-table-column label="设备位置" align="center" prop="deviceLocation"/>
        <el-table-column label="二维码" align="center" prop="deviceQrCode">
          <template #default="scope">
            <el-button link type="primary" @click="getDeviceQrCode(scope.row)">二维码</el-button>
          </template>
        </el-table-column>
        <el-table-column label="公众号二维码" align="center" prop="deviceMpQrCode">
          <template #default="scope">
            <el-button link type="primary" @click="getDeviceMpQrCode(scope.row)">公众号二维码</el-button>
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="device_status" :value="scope.row.status"/>
          </template>
        </el-table-column>

        <el-table-column label="押金金额" align="center" prop="depositAmount"/>
        <el-table-column label="收费类型" align="center" prop="feeType">
          <template #default="scope">
            <dict-tag :options="fee_type" :value="scope.row.feeType"/>
          </template>
        </el-table-column>
        <el-table-column label="收费规则" align="center" prop="feeConfig">
          <template #default="scope">
            <el-button link type="primary" @click="getFeeConfig(scope.row)" :disabled="scope.row.feeType === 'free'">
              收费规则
            </el-button>
          </template>
        </el-table-column>


        <el-table-column label="渠道" align="center" prop="channel">
          <template #default="scope">
            <dict-tag :options="channel_type" :value="scope.row.channel"/>
          </template>
        </el-table-column>


        <el-table-column label="建立时间" align="center" prop="connectTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.connectTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="掉线时间" align="center" prop="lossTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lossTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="格子数量" align="center" prop="gardNum"/>
        <el-table-column label="后台账号" align="center" prop="adminUser"/>
        <el-table-column label="后台密码" align="center" prop="adminPwd" show-overflow-tooltip/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="Imli" align="center" prop="deviceImei"/>
        <el-table-column label="设备卡号" align="center" prop="deviceCardNo"/>
        <el-table-column label="ICCID" align="center" prop="deviceIccid"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
          <template #default="scope">
            <el-tooltip content="指令" placement="top">
              <el-button link type="primary" icon="Open" @click="handleOper(scope.row)">指令</el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['device:device:edit']">修改
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['device:device:remove']">删除
              </el-button>
            </el-tooltip>
            <el-tooltip content="柜子信息" placement="top">
              <el-button link type="primary" icon="Grid" @click="handleAuthRole(scope.row)"
                         v-hasPermi="['device:device:edit']">柜子信息
              </el-button>
            </el-tooltip>
            <el-tooltip content="导入柜子" placement="top">
              <el-button link type="primary" icon="Upload" @click="handleImportGrid(scope.row)"
                         v-hasPermi="['device:device:edit']">导入柜子
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" :disabled="editable">
            <el-option
              v-for="dict in device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备场地" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择">
            <el-option
              v-for="item in positionList"
              :key="item.positionId"
              :label="item.name"
              :value="item.positionId"
              :disabled="item.status == 'discard'"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="设备描述" prop="describe">
          <el-input v-model="form.describe" placeholder="请输入设备描述" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="设备位置" prop="deviceLocation">
          <el-input v-model="form.deviceLocation" placeholder="请输入设备位置" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择设备状态">
            <el-option
              v-for="dict in device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="渠道" prop="channel">-->
<!--          <el-input v-model="form.channel" placeholder="请输入渠道" maxlength="20" show-word-limit/>-->
<!--        </el-form-item>-->
        <el-form-item label="后台账号" prop="adminUser">
          <el-input v-model="form.adminUser" placeholder="请输入后台账号" maxlength="10" show-word-limit/>
        </el-form-item>
        <el-form-item label="后台密码" prop="adminPwd">
          <el-input v-model="form.adminPwd" placeholder="请输入后台密码" maxlength="10" show-word-limit/>
        </el-form-item>
        <el-form-item label="收费类型" prop="feeType">
          <el-select v-model="form.feeType" placeholder="请选择收费类型" @change="handleFeeTypeChange">
            <el-option
              v-for="dict in fee_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="押金金额" prop="depositAmount" v-if="depositAmountEnabled">
          <el-input-number :min="1" v-model="form.depositAmount" placeholder="输入押金金额" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="大柜单价" prop="largeGridPrice" v-if="hourEnabled  || timesEnabled">
          <el-input-number :min="0" v-model="form.largeGridPrice" placeholder="输入大柜单价" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="大柜封顶价" prop="largeGridMaxPrice" v-if="hourEnabled">
          <el-input-number :min="0" v-model="form.largeGridMaxPrice" placeholder="输入大柜封顶价" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="中柜单价" prop="commonGridPrice" v-if="hourEnabled  || timesEnabled">
          <el-input-number :min="0" v-model="form.commonGridPrice" placeholder="输入中柜单价" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="中柜封顶价" prop="commonGridMaxPrice" v-if="hourEnabled">
          <el-input-number :min="0" v-model="form.commonGridMaxPrice" placeholder="输入中柜封顶价" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="小柜单价" prop="smallGridPrice" v-if="hourEnabled || timesEnabled">
          <el-input-number :min="0" v-model="form.smallGridPrice" placeholder="输入小柜单价" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="小格封顶价" prop="smallGridMaxPrice" v-if="hourEnabled">
          <el-input-number :min="0" v-model="form.smallGridMaxPrice" placeholder="输入小格封顶价" controls-position="right" :precision="2"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="50" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--    二维码弹框-->
    <el-dialog
      title="设备二维码"
      v-model="deviceQrCodeDialogVisible">
      <div>
        <img :src="qrCodeUrl" alt="QR Code" style="margin: auto; display: block;"/>
      </div>
      <br/>
      <div class="dialog-footer" align='right'>
        <el-button @click="deviceQrCodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deviceQrCodeDialogVisible = false">确 定</el-button>
        <el-button type="success" @click="downloadRes">下载二维码</el-button>
      </div>
    </el-dialog>

    <!--    公众号二维码弹框-->
    <el-dialog
      title="设备公众号二维码"
      v-model="deviceMpQrCodeDialogVisible">
      <div>
        <img :src="mpQrCodeUrl" alt="QR Code" style="margin: auto; display: block;"/>
      </div>
      <br/>
      <div class="dialog-footer" align='right'>
        <el-button @click="deviceMpQrCodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deviceMpQrCodeDialogVisible = false">确 定</el-button>
        <el-button type="success" @click="downloadMpRes">下载二维码</el-button>
      </div>
    </el-dialog>

    <!--设备操作指令-->
    <el-dialog
      title="设备指令发送"
      v-model="deviceOperDialogVisible"
      width="35%">
      <p style="font-weight: bold;">设备号: {{ operRow.deviceNo }}</p>

      <el-button @click="handleOperDommand(operRow.deviceNo,'2','重启设备')">重启设备</el-button>
      <el-button type="primary" @click="handleOperDommand(operRow.deviceNo,'3','推送设备信息')">推送设备信息</el-button>
      <el-button type="success" @click="handleOperDommand(operRow.deviceNo,'4','全部开柜')">全部开柜</el-button>
      <el-button type="info" @click="handleOperDommand(operRow.deviceNo,'5','同步设备柜子')">同步设备柜子</el-button>
      <br/>
      <br/>
      <el-button type="warning" @click="handleOperDommand(operRow.deviceNo,'6','推送柜子状态')">推送柜子状态</el-button>
      <el-button type="primary" @click="handleOperDommand(operRow.deviceNo,'9','推送蓝牙版本')">推送蓝牙版本</el-button>
      <el-button type="success" @click="handleOperDommand(operRow.deviceNo,'11','推送所有订单')">推送所有订单
      </el-button>
      <el-button type="info" @click="handleOperDommand(operRow.deviceNo,'12','获取SIM卡信息')">获取SIM卡信息</el-button>
      <br/>
      <br/>
      <el-button type="warning" @click="handleOperDommand(operRow.deviceNo,'13','进入设备后台')">进入设备后台
      </el-button>
      <el-button @click="handleOperDommand(operRow.deviceNo,'14','推送设备密码')">推送设备密码</el-button>
      <el-button type="primary" @click="handleOperDommand(operRow.deviceNo,'15','发送上传日志指令')">发送上传日志指令
      </el-button>
      <el-button type="success" @click="handleOperDommand(operRow.deviceNo,'16','发送删除日志指令')">发送删除日志指令
      </el-button>
      <br/>
      <br/>
    </el-dialog>

    <!--    设备导入格子-->
    <el-dialog
      title="导入格子"
      v-model="importGridDialogVisible"
      :limit="1"
      width="35%">
      <p style="font-weight: bold;">设备号: {{ importRow.deviceNo }}</p>
      <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload"
                 accept=".xlsx, .xls">
        <el-button type="primary">
          选择需要导入的Excel文件
          <el-icon class="el-icon--right">
            <Upload/>
          </el-icon>
        </el-button>
      </el-upload>
      <br/>
      <div class="text-center el-upload__tip">
        <span>仅允许导入xls、xlsx格式文件。</span>
        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                 @click="importTemplate(importRow.deviceType)">下载模板
        </el-link>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!--          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>-->
          <el-button @click="importGridCancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!--收费配置-->
    <el-dialog
      :title = "feeConfigTitle"
      v-model="feeConfigVisible"
      width="30%">
      <el-table :data="feeConfigData.value">
        <el-table-column label="规格" align="center" prop="specCode">
          <template #default="scope">
            <dict-tag :options="grid_spec" :value="scope.row.specCode"/>
          </template>
        </el-table-column>
        <el-table-column property="maxHour" label="封顶价" width="200" v-if="hoursColumn"></el-table-column>
        <el-table-column property="hourPrice" label="单价(小时)" width="200" v-if="hoursColumn"></el-table-column>
        <el-table-column property="timesPrice" label="单次价" v-if="tiemsColumn"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Device" lang="ts">
import {addDevice, delDevice, getDevice, importGrid, listDevice, operDommand, updateDevice} from '@/api/device/device';
import {DeviceForm, DeviceQuery, DeviceVO} from '@/api/device/device/types';
import {allPosition, getPosition} from "@/api/device/position";
import ResetPwd from "@/views/system/user/profile/resetPwd.vue";
import {PositionVO} from "@/api/device/position/types";

const router = useRouter();

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {device_status, fee_type,grid_spec} = toRefs<any>(proxy?.useDict('device_status', 'fee_type','grid_spec'));
const {device_type} = toRefs<any>(proxy?.useDict('device_type'));
const { channel_type } = toRefs<any>(proxy?.useDict('channel_type'));

const deviceList = ref<DeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deviceQrCodeDialogVisible = ref(false);
const deviceMpQrCodeDialogVisible=ref(false);
const deviceOperDialogVisible = ref(false);
const importGridDialogVisible = ref(false);
const editable = ref(false);

const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();
const positions = [];

const depositAmountEnabled = ref(true);
const hourEnabled = ref(false);
const timesEnabled = ref(false);

const hoursColumn = ref(false);
const tiemsColumn = ref(false);
const feeConfigVisible = ref(false);
const feeConfigTitle = ref('');

const feeConfigData = [];

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceForm = {
  deviceId: undefined,
  deviceNo: undefined,
  deviceType: undefined,
  devicePwd: undefined,
  positionId: undefined,
  name: undefined,
  describe: undefined,
  deviceLocation: undefined,
  status: undefined,
  channel: undefined,
  connectTime: undefined,
  lossTime: undefined,
  gardNum: undefined,
  adminUser: undefined,
  adminPwd: undefined,
  remark: undefined,
  depositAmount: undefined,
  feeType: undefined,
  feeConfig: undefined,
  largeGridPrice: 0,
  largeGridMaxPrice: 0,
  commonGridPrice: 0,
  commonGridMaxPrice: 0,
  smallGridPrice: 0,
  smallGridMaxPrice: 0,
}
const data = reactive<PageData<DeviceForm, DeviceQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'create_time',
    isAsc: 'desc',
    deviceNo: undefined,
    deviceType: undefined,
    devicePwd: undefined,
    positionId: undefined,
    name: undefined,
    describe: undefined,
    deviceLocation: undefined,
    status: undefined,
    channel: undefined,
    connectTime: undefined,
    lossTime: undefined,
    gardNum: undefined,
    adminUser: undefined,
    adminPwd: undefined,
    params: {}
  },
  qrCodeUrl: undefined,
  mpQrCodeUrl:undefined,
  positionList: [],
  operRow: undefined,
  importRow: undefined,
  rules: {
    deviceId: [
      {required: true, message: "设备ID不能为空", trigger: "blur"}
    ],
    deviceType: [
      {required: true, message: "设备类型不能为空", trigger: "change"}
    ],
    positionId: [
      {required: true, message: "场地不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "设备名称不能为空", trigger: "blur"}
    ],
    describe: [
      {required: true, message: "设备描述不能为空", trigger: "blur"}
    ],
    deviceLocation: [
      {required: true, message: "设备位置不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "设备状态", trigger: "change"}
    ],

    adminUser: [
      {required: true, message: "后台账号不能为空", trigger: "blur"}
    ],
    adminPwd: [
      {required: true, message: "后台密码不能为空", trigger: "blur"}
    ],
    depositAmount: [
      { required: true, message: "押金金额不能为空", trigger: "blur" }
    ],
    feeType: [
      { required: true, message: "收费类型：free 免费  hour 小时, times 按次，special 特殊方式不能为空", trigger: "change" }
    ],
    largeGridPrice: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    largeGridMaxPrice: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    commonGridPrice: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    commonGridMaxPrice: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    smallGridPrice: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    smallGridMaxPrice: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
  }
});

const {queryParams, form, rules, positionList, qrCodeUrl,mpQrCodeUrl, operRow, importRow} = toRefs(data);


/** 下载模板操作 */
const importTemplate = (type: any) => {
  let fileName = type == "bluetooth" ? '蓝牙设备-柜子导入模版.xlsx' : '串口设备-柜子导入模版.xlsx';
  proxy?.download("/device/device/importTemplate/" + type, {}, fileName);
}


function handleFeeTypeChange(val: string) {
  if (val ==='free'){
    hourEnabled.value = false;
    timesEnabled.value = false;
  }else if (val === 'hour') {
    hourEnabled.value= true;
    timesEnabled.value = false;
    depositAmountEnabled.value = true;
  }else if (val === 'times') {
    hourEnabled.value= false;
    hourEnabled.value = false;
    timesEnabled.value= true;
    depositAmountEnabled.value = true;
  }
}

const getFeeConfig = async (row?: DeviceVO) => {
  console.log("row",row);
  feeConfigVisible.value = true;
  feeConfigData.value = JSON.parse(row.feeConfig);
  if (row.feeType === 'hour'){
    feeConfigTitle.value = row.name+"： 收费配置(按小时)";
    tiemsColumn.value = false;
    hoursColumn.value = true;
  }
  if (row.feeType === 'times'){
    feeConfigTitle.value = row.name+"： 收费配置(按次)";
    tiemsColumn.value = true;
    hoursColumn.value = false;
  }
}

const downloadRes = async () => {
  let response = await fetch(qrCodeUrl.value)
  let blob = await response.blob()
  let objectUrl = window.URL.createObjectURL(blob)
  let a = document.createElement('a')
  a.href = objectUrl
  a.download = 'qrcode.jpg'
  a.click()
  a.remove()
}

const downloadMpRes = async () => {
  let response = await fetch(mpQrCodeUrl.value)
  let blob = await response.blob()
  let objectUrl = window.URL.createObjectURL(blob)
  let a = document.createElement('a')
  a.href = objectUrl
  a.download = 'qrcode.jpg'
  a.click()
  a.remove()
}

/** 覆盖默认上传行为 */
const requestUpload = async (file: any) => {
  await importGrid(file, importRow.value.deviceNo);
  proxy?.$modal.msgSuccess("导入成功");
  importGridDialogVisible.value = false;
};


const handleAuthRole = (row: DeviceVO) => {
  const deviceNo = row.deviceNo;
  const deviceId = row.deviceId;
  const positionId = row.positionId;
  //router.push("/device/device-grid/deviceNo/" + deviceNo);
  router.push({name: 'deviceGrid', params: {deviceNo, deviceId, positionId}});
}

/** 查询设备信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDevice(queryParams.value);
  deviceList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
}

const getPositionList = async () => {
  loading.value = true;
  const res = await allPosition();
  positionList.value = res.data;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

const importGridCancel = () => {
  importGridDialogVisible.value = false;
}

/** 上传预处理 */
const beforeUpload = (file: any) => {
  if (file.type !== "application/vnd.ms-excel" && file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
    proxy?.$modal.msgError("文件格式错误，请上传Excel类型文件，如：xls 或 xlsx 后缀的文件。");
  }
  // else {
  //   const reader = new FileReader();
  //   reader.readAsDataURL(file);
  //   reader.onload = () => {
  //     options.img = reader.result;
  //     options.fileName = file.name;
  //   };
  // }
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  deviceFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceVO[]) => {
  ids.value = selection.map(item => item.deviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  timesEnabled.value = false;
  hourEnabled.value = false;
  dialog.visible = true;
  dialog.title = "添加设备信息";
  editable.value = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceVO) => {
  reset();
  const _deviceId = row?.deviceId || ids.value[0]
  const res = await getDevice(_deviceId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备信息";

  feeConfigData.value = JSON.parse(row.feeConfig);
  if (row.feeType ==='free'){
    hourEnabled.value = false;
    timesEnabled.value = false;
    form.value.largeGridPrice = 0;
    form.value.largeGridMaxPrice = 0;
    form.value.commonGridPrice = 0;
    form.value.commonGridMaxPrice = 0;
    form.value.smallGridPrice = 0;
    form.value.smallGridMaxPrice = 0;
  }else if (row.feeType === 'hour') {
    hourEnabled.value= true;
    timesEnabled.value= false;
    depositAmountEnabled.value = true;
    let small = feeConfigData.value.find(item => item.specCode === 'small');
    form.value.smallGridPrice = small.hourPrice;
    form.value.smallGridMaxPrice = small.maxHourPrice;
    let common = feeConfigData.value.find(item => item.specCode === 'common');
    form.value.commonGridPrice = common.hourPrice;
    form.value.commonGridMaxPrice = common.maxHourPrice;
    let large = feeConfigData.value.find(item => item.specCode === 'large');
    form.value.largeGridPrice = large.hourPrice;
    form.value.largeGridMaxPrice = large.maxHourPrice;
  }else if (row.feeType === 'times') {
    depositAmountEnabled.value = true;
    hourEnabled.value= false;
    timesEnabled.value= true;
    depositAmountEnabled.value = true;
    let small = feeConfigData.value.find(item => item.specCode === 'small');
    form.value.smallGridPrice = small.timesPrice;
    form.value.smallGridMaxPrice = small.timesPrice;
    let common = feeConfigData.value.find(item => item.specCode === 'common');
    form.value.commonGridPrice = common.timesPrice;
    form.value.commonGridMaxPrice = common.timesPrice;
    let large = feeConfigData.value.find(item => item.specCode === 'large');
    form.value.largeGridPrice = large.timesPrice;
    form.value.largeGridMaxPrice = large.timesPrice;
  }

  editable.value = true;
}

/**
 * 生成二维码
 * @param row
 */
const getDeviceQrCode = async (row?: DeviceVO) => {
  try {
    qrCodeUrl.value = row.deviceQrCode;
    deviceQrCodeDialogVisible.value = true;
  } catch (error) {
    console.error('Failed to generate QR code', error);
  }
}
const getDeviceMpQrCode = async (row?: DeviceVO) => {
  try {
    mpQrCodeUrl.value = row.deviceMpQrCode;
    deviceMpQrCodeDialogVisible.value = true;
  } catch (error) {
    console.error('Failed to generate QR code', error);
  }
}


const handleOper = async (row?: DeviceVO) => {
  deviceOperDialogVisible.value = true;
  operRow.value = row;
}

const handleImportGrid = async (row?: DeviceVO) => {
  importGridDialogVisible.value = true;
  importRow.value = row;
}

const handleOperDommand = async (deviceNo, operType, operTypeName) => {
  await proxy?.$modal.confirm('确定执行' + operTypeName + '操作？').finally(() => loading.value = false);
  await operDommand(deviceNo, operType);
  proxy?.$modal.msgSuccess("执行成功");
  //deviceOperDialogVisible.value = false;
  //await getList();
}


/** 提交按钮 */
const submitForm = () => {
  deviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      let  feeType = form.value.feeType;
      let  largeGridPrice = 0;
      let  largeGridMaxPrice = 0;
      let  commonGridPrice = 0;
      let  commonGridMaxPrice = 0;
      let  smallGridPrice = 0;
      let  smallGridMaxPrice = 0;
      if (feeType === 'times'){
        largeGridPrice = form.value.largeGridPrice;
        largeGridMaxPrice = form.value.largeGridPrice;
        commonGridPrice = form.value.commonGridPrice;
        commonGridMaxPrice = form.value.commonGridPrice;
        smallGridPrice = form.value.smallGridPrice;
        smallGridMaxPrice = form.value.smallGridPrice;
        form.value.feeConfig = `[{"specCode":"small","timesPrice":${smallGridPrice},"hourPrice":0,"maxHourPrice":0,"maxHour":0},` +
          `{"specCode":"common","timesPrice":${commonGridPrice},"hourPrice":0,"maxHourPrice":0,"maxHour":0},` +
          `{"specCode":"large","timesPrice":${largeGridPrice},"hourPrice":0,"maxHourPrice":0,"maxHour":0}]`;
      }
      if (feeType === 'hour'){
        largeGridPrice = form.value.largeGridPrice;
        largeGridMaxPrice = form.value.largeGridMaxPrice;
        commonGridPrice = form.value.commonGridMaxPrice;
        commonGridMaxPrice = form.value.commonGridMaxPrice;
        smallGridPrice = form.value.smallGridPrice;
        smallGridMaxPrice = form.value.smallGridMaxPrice;
        form.value.feeConfig = `[{"specCode":"small","timesPrice":0,"hourPrice":${smallGridPrice},"maxHourPrice":${smallGridMaxPrice},"maxHour":0},` +
          `{"specCode":"common","timesPrice":0,"hourPrice":${commonGridPrice},"maxHourPrice":${commonGridMaxPrice},"maxHour":0},` +
          `{"specCode":"large","timesPrice":0,"hourPrice":${largeGridPrice},"maxHourPrice":${largeGridMaxPrice},"maxHour":0}]`;
      }

      if (form.value.deviceId) {
        await updateDevice(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addDevice(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceVO) => {
  const _deviceIds = row?.deviceId || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备信息编号为"' + _deviceIds + '"的数据项？').finally(() => loading.value = false);
  await delDevice(_deviceIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getPositionList();
});
</script>
